import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.pms.medialibrary.commons.dataobjects.DOAgeRating;
import net.pms.medialibrary.commons.dataobjects.DORating;
import net.pms.medialibrary.commons.helpers.TmdbHelper;
import net.sf.jtmdb.CastInfo;
import net.sf.jtmdb.Genre;
import net.sf.jtmdb.Movie;
import net.sf.jtmdb.MoviePoster;

public class TMDbPlugin implements MovieInfoPlugin {
	private static final Logger log = LoggerFactory.getLogger(TMDbPlugin.class);
	private Movie movie;

	public TMDbPlugin() {
	    TmdbHelper.initialize();
	}

	@Override
    public void importByTitle(String title) {
		if(log.isDebugEnabled()) log.debug("importing TMDb movie with title: " + title);
	    try {
	        List<Movie> movies = Movie.search(title);
			if (movies != null && movies.size() > 0) {
				movie = Movie.getInfo(movies.get(0).getID());
				String moviesStr = String.format("Movie matched for '%s' on TMDb has id=%s, name='%s'", title, movies.get(0).getID(), movies.get(0).getName());
				if(movies.size() > 1){
					moviesStr += ". other (not considered) matches are ";
					for(int i = 1; i < movies.size(); i++){
						moviesStr += String.format("id=%s, name='%s';", movies.get(i).getID(), movies.get(i).getName());
					}
					moviesStr = moviesStr.substring(0, moviesStr.length() - 2);
				}
				if(log.isInfoEnabled()) log.info(moviesStr);
			}
        } catch (Exception e) {
        	log.error(String.format("Failed to retrieve movie with title '%s'", title), e);
        }
	    
    }

	@Override
    public DOAgeRating getAgeRating() {
		String level = movie == null ? "" : movie.getCertification();
		String reason = "";
	    return new DOAgeRating(level, reason);
    }

	@Override
    public String getCoverURL() {
		MoviePoster cover = movie == null ? null : !movie.getImages().posters.iterator().hasNext() ? null : movie.getImages().posters.iterator().next();
	    return cover == null ? "" : cover.getLargestImage().toString();
    }

	@Override
    public String getDirector() {
		String res = "";
		if(movie != null && movie.getCast() != null){
		    for(CastInfo ci : movie.getCast()){
		    	if(ci.getJob().equals("Director")){
		    		res = ci.getName();
		    		break;
		    	}
		    }			
		}	    
	    return res;
    }

	@Override
    public List<String> getGenres() {
		ArrayList<String> res = new ArrayList<String>();
		if(movie != null && movie.getGenres() != null){
		    for(Genre ci : movie.getGenres()){
		    		res.add(ci.getName());
		    }			
		}
	    return res;
    }

	@Override
    public List<String> getImages() {
		ArrayList<String> res = new ArrayList<String>();

		if(movie != null){
			while(movie.getImages().posters.iterator().hasNext()){
				res.add(movie.getImages().posters.iterator().next().getLargestImage().getPath().toString());
			}
			
			while(movie.getImages().backdrops.iterator().hasNext()){
				res.add(movie.getImages().backdrops.iterator().next().getLargestImage().getPath());
			}			
		}
	    return res;
    }

	@Override
    public String getPlot() {
	    return movie == null || movie.getOverview().equals("null") ? "" : movie.getOverview();
    }

	@Override
    public DORating getRating() {
		int rating = movie == null ? 0 : (int)(movie.getRating() * 10);
		int votes = movie == null ? 0 : movie.getVotes();
	    return new DORating(rating, votes);
    }

	@Override
    public String getTagline() {
	    return movie == null ? "" : movie.getTagline();
    }

	@Override
    public String getTitle() {
	    return movie == null ? "" : movie.getName();
    }

	@SuppressWarnings("deprecation")
    @Override
    public int getYear() {
	    return movie == null || movie.getReleasedDate() == null ? 0 : movie.getReleasedDate().getYear() + 1900;
    }

	@Override
    public int getBudget() {
	    return movie == null ? 0 : movie.getBudget();
    }

	@Override
    public String getHomepageUrl() {
	    return movie == null || movie.getHomepage() == null ? "" : movie.getHomepage().toString();
    }

	@Override
    public String getImdbId() {
	    return movie == null ? "" : movie.getImdbID();
    }

	@Override
    public String getOriginalName() {
	    return movie == null ? "" : movie.getOriginalName();
    }

	@Override
    public int getRevenue() {
	    return movie == null ? 0 : movie.getRevenue();
    }

	@Override
    public String getTmdbId() {
	    return movie == null ? "" : String.valueOf(movie.getID());
    }

	@Override
    public String getTrailerUrl() {
	    return movie == null || movie.getTrailer() == null ? "" : movie.getTrailer().toString();
    }

}
